package com.xiantm.study.thread.towparsetermination.jdk.cyclicbarrier;


import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 循环屏障
 * 所有线程都达到预定条件才会进入下一项操作。
 */
public class Main {

    public static final int THREAD = 3;
    public static void main(String[] args) {
        System.out.println("BEGIN");
        ExecutorService service = Executors.newFixedThreadPool(THREAD);
        Runnable barrierAction = () -> System.out.println("Barrier Action");
        CountDownLatch doneLatch = new CountDownLatch(THREAD);
        CyclicBarrier cyclicBarrier = new CyclicBarrier(THREAD, barrierAction);
        try{
            for (int i = 0; i < THREAD; i++) {
                service.execute(new MyTask(cyclicBarrier,doneLatch,i));
            }
            System.out.println("AWAIT");
            doneLatch.await();
        } catch (InterruptedException ignored){}
        finally {
            service.shutdown();
            System.out.println("END");
        }
    }
}
